package com.southminority.ethnic.service.organization.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.southminority.ethnic.common.exception.BusinessException;
import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.mapper.organization.OrganizationMapper;
import com.southminority.ethnic.pojo.otherPojo.Organization;
import com.southminority.ethnic.service.organization.OrganizationService;
import com.southminority.ethnic.controller.organization.vo.OrganizationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 机构组织服务实现类.
 * <p>
 * 实现了 {@link OrganizationService} 接口，负责处理所有与机构组织相关的业务逻辑。
 * 包括数据查询、转换、增删改查等操作，并处理了多个JSON格式字段的序列化与反序列化。
 * 
 * @author SouthMinority
 */
@Slf4j
@Service
public class OrganizationServiceImpl implements OrganizationService {

    private final OrganizationMapper organizationMapper;
    private final ObjectMapper objectMapper;

    public OrganizationServiceImpl(OrganizationMapper organizationMapper, ObjectMapper objectMapper) {
        this.organizationMapper = organizationMapper;
        this.objectMapper = objectMapper;
    }

    // =================================================================================
    // ==                             前端展示相关方法 (Public API)                     ==
    // =================================================================================

    @Override
    public List<OrganizationVO> getHomepageOrganizationList() {
        QueryWrapper<Organization> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .eq("is_featured", 1)
               .gt("homepage_order", 0)
               .orderByAsc("homepage_order");

        List<Organization> organizationList = organizationMapper.selectList(wrapper);
        return organizationList.stream()
                              .map(this::convertToVO)
                              .collect(Collectors.toList());
    }

    @Override
    public List<OrganizationVO> getTeamDisplayOrganizationList() {
        QueryWrapper<Organization> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .eq("is_team_display", 1)
               .orderByAsc("sort_order")
               .orderByDesc("create_time");
        List<Organization> list = organizationMapper.selectList(wrapper);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public OrganizationVO getOrganizationDetail(Long id) {
        Organization organization = organizationMapper.selectById(id);
        if (organization == null || organization.getStatus() != 1) {
            throw new BusinessException("机构信息不存在或未启用");
        }
        
        increaseViewCount(id);
        organization = organizationMapper.selectById(id);
        
        return convertToVO(organization);
    }

    @Override
    public List<OrganizationVO> getAllOrganizationList() {
        QueryWrapper<Organization> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .orderByAsc("sort_order")
               .orderByDesc("create_time");
        
        List<Organization> organizationList = organizationMapper.selectList(wrapper);
        return organizationList.stream()
                              .map(this::convertToVO)
                              .collect(Collectors.toList());
    }


    // =================================================================================
    // ==                             后台管理相关方法 (Admin API)                      ==
    // =================================================================================

    @Override
    public PageResult<OrganizationVO> getOrganizationPageForAdmin(Integer page, Integer size, String keyword, String organizationType, Integer status) {
        Page<Organization> pageObj = new Page<>(page, size);
        QueryWrapper<Organization> wrapper = new QueryWrapper<>();

        if (StringUtils.hasText(keyword)) {
            wrapper.like("name", keyword);
        }
        if (StringUtils.hasText(organizationType)) {
            wrapper.eq("organization_type", organizationType);
        }
        if (status != null) {
            wrapper.eq("status", status);
        } else {
            wrapper.ne("status", -1);
        }

        wrapper.orderByDesc("is_featured").orderByAsc("sort_order").orderByDesc("create_time");

        IPage<Organization> pageResult = organizationMapper.selectPage(pageObj, wrapper);

        List<OrganizationVO> voList = pageResult.getRecords().stream()
                                       .map(this::convertToVO)
                                       .collect(Collectors.toList());

        return PageResult.<OrganizationVO>builder()
                .current(pageResult.getCurrent())
                .size(pageResult.getSize())
                .total(pageResult.getTotal())
                .pages(pageResult.getPages())
                .records(voList)
                .build();
    }

    @Override
    public OrganizationVO getOrganizationDetailForAdmin(Long id) {
        Organization organization = organizationMapper.selectById(id);
        if (organization == null) {
            throw new BusinessException("机构信息不存在");
        }
        return convertToVO(organization);
    }

    @Override
    @Transactional
    public OrganizationVO createOrganization(Organization organization) {
        if (organization == null) {
            throw new BusinessException("机构信息不能为空");
        }
        
        organization.setCreateTime(LocalDateTime.now());
        organization.setUpdateTime(LocalDateTime.now());
        organizationMapper.insert(organization);
        
        return convertToVO(organization);
    }

    @Override
    @Transactional
    public OrganizationVO updateOrganization(Long id, Organization organization) {
        Organization existingOrganization = organizationMapper.selectById(id);
        if (existingOrganization == null) {
            throw new BusinessException("机构信息不存在");
        }

        organization.setId(id);
        organization.setUpdateTime(LocalDateTime.now());
        organizationMapper.updateById(organization);
        
        return convertToVO(organizationMapper.selectById(id));
    }

    @Override
    @Transactional
    public boolean deleteOrganization(Long id) {
        Organization organization = organizationMapper.selectById(id);
        if (organization == null) {
            return true;
        }

        organization.setStatus(-1);
        organization.setUpdateTime(LocalDateTime.now());
        return organizationMapper.updateById(organization) > 0;
    }

    @Override
    @Transactional
    public boolean batchDeleteOrganizations(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("ID列表不能为空");
        }
        
        List<Organization> organizationList = organizationMapper.selectBatchIds(ids);
        if (organizationList.isEmpty()) {
            return true;
        }

        LocalDateTime now = LocalDateTime.now();
        for (Organization organization : organizationList) {
            organization.setStatus(-1);
            organization.setUpdateTime(now);
            organizationMapper.updateById(organization);
        }
        
        return true;
    }

    @Override
    @Transactional
    public boolean updateOrganizationStatus(Long id, Integer status) {
        Organization organization = organizationMapper.selectById(id);
        if (organization == null) {
            throw new BusinessException("机构信息不存在");
        }
        if (status == null || (status < -1 || status > 1)) {
            throw new BusinessException("无效的状态值");
        }

        organization.setStatus(status);
        organization.setUpdateTime(LocalDateTime.now());
        return organizationMapper.updateById(organization) > 0;
    }

    @Override
    @Transactional
    public boolean setOrganizationFeatured(Long id, Integer isFeatured) {
        Organization organization = organizationMapper.selectById(id);
        if (organization == null) {
            throw new BusinessException("机构信息不存在");
        }
        if (isFeatured == null || (isFeatured != 0 && isFeatured != 1)) {
            throw new BusinessException("无效的首页展示值");
        }
        organization.setIsFeatured(isFeatured);
        organization.setUpdateTime(LocalDateTime.now());
        return organizationMapper.updateById(organization) > 0;
    }

    @Override
    @Transactional
    public boolean setOrganizationTeamDisplay(Long id, Integer display) {
        Organization organization = organizationMapper.selectById(id);
        if (organization == null) {
            throw new BusinessException("机构信息不存在");
        }
        if (display == null || (display != 0 && display != 1)) {
            throw new BusinessException("无效的团队展示值");
        }
        organization.setIsTeamDisplay(display);
        organization.setUpdateTime(LocalDateTime.now());
        return organizationMapper.updateById(organization) > 0;
    }

    // =================================================================================
    // ==                             私有辅助方法 (Private Helpers)                      ==
    // =================================================================================

    /**
     * 将 Organization POJO 转换为 OrganizationVO DTO.
     * <p>
     * 此方法负责处理复杂数据类型的转换，例如将数据库中存储的JSON字符串
     * 转换为Java的List或Map，以便前端可以直接使用。
     *
     * @param organization 数据库实体对象
     * @return 用于前端展示的视图对象
     */
    private OrganizationVO convertToVO(Organization organization) {
        if (organization == null) return null;
        
        OrganizationVO vo = new OrganizationVO();
        BeanUtils.copyProperties(organization, vo);
        
        try {
            if (StringUtils.hasText(organization.getImageUrls())) {
                vo.setImageUrls(objectMapper.readValue(organization.getImageUrls(), new TypeReference<List<String>>() {}));
            } else {
                vo.setImageUrls(Collections.emptyList());
            }
            
            if (StringUtils.hasText(organization.getResearchDirections())) {
                vo.setResearchDirections(objectMapper.readValue(organization.getResearchDirections(), new TypeReference<List<String>>() {}));
            } else {
                vo.setResearchDirections(Collections.emptyList());
            }
            
            if (StringUtils.hasText(organization.getContactInfo())) {
                vo.setContactInfo(objectMapper.readValue(organization.getContactInfo(), new TypeReference<Map<String, Object>>() {}));
            }
        } catch (JsonProcessingException e) {
            log.error("解析机构(ID:{})的JSON字段失败: {}", organization.getId(), e.getMessage());
            // 设置默认空值，避免前端出错
            vo.setImageUrls(Collections.emptyList());
            vo.setResearchDirections(Collections.emptyList());
            vo.setContactInfo(Collections.emptyMap());
        }
        
        return vo;
    }

    /**
     * 内部方法：安全地增加一次机构浏览次数.
     * @param id 机构ID
     */
    private void increaseViewCount(Long id) {
        Organization organization = organizationMapper.selectById(id);
        if (organization != null) {
            organization.setViewCount((organization.getViewCount() == null ? 0 : organization.getViewCount()) + 1);
            organization.setUpdateTime(LocalDateTime.now());
            organizationMapper.updateById(organization);
        }
    }
} 
